package com.stylefeng.guns.modular.huamao.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.huamao.dao.SktSysConfigsMapper;
import com.stylefeng.guns.modular.huamao.dao.SktWorkorderMapper;
import com.stylefeng.guns.modular.huamao.model.Account;
import com.stylefeng.guns.modular.huamao.model.AccountShop;
import com.stylefeng.guns.modular.huamao.model.SktSysConfigs;
import com.stylefeng.guns.modular.huamao.model.SktWorkorder;
import com.stylefeng.guns.modular.huamao.model.Users;
import com.stylefeng.guns.modular.huamao.service.IAccountService;
import com.stylefeng.guns.modular.huamao.service.IAccountShopService;
import com.stylefeng.guns.modular.huamao.service.IAppUserService;
import com.stylefeng.guns.modular.huamao.service.IAppWorkorderServer;
import com.stylefeng.guns.modular.huamao.service.IUsersService;
import com.stylefeng.guns.modular.huamao.util.CacheUtil;
import com.stylefeng.guns.modular.huamao.util.MSGUtil;
import com.stylefeng.guns.modular.huamao.util.StringUtils;

@Service
public class AppWorkorderServerImpl extends ServiceImpl<SktWorkorderMapper,SktWorkorder> implements IAppWorkorderServer {
	
	@Autowired
	private SktWorkorderMapper sktWorkorderMapper;
	@Autowired
	private IUsersService iUsersService;
	@Autowired
	private IAccountService iAccountService;
	@Autowired
	private SktSysConfigsMapper sktSysConfigsMapper;
	@Autowired
	private IAccountShopService iAccountShopService;
	@Autowired
	private CacheUtil cacheUtil;
	@Autowired
    private IAppUserService appUserService;
	@Transactional
	@Override
	public Map<String, Object> buyWorkorder(String orderNo, Integer payType, String payPwd, Users user) {
		try{
			
			Map<String,Object> map = new HashMap<String,Object>();
			Integer userId = user.getUserId();
			//验证支付密码
			JSONObject checkPayPassWorld = iUsersService.checkPayPassWorld(userId,payPwd);
			if("00".equals(checkPayPassWorld.get("code"))){
				map.put("msg", checkPayPassWorld.get("msg"));
				return map;
			}
			
			//根据orderno  userid 查询workerder表
			//返回orderid totalmoney  orderno 字段
			Map<String,Object> selWorkorderMap = new HashMap<>();
			selWorkorderMap.put("orderNo", orderNo);
			selWorkorderMap.put("userId", userId);
			Map<String,Object> selWorkordeData = sktWorkorderMapper.selWorkordeData(selWorkorderMap);
			if(ToolUtil.isEmpty(selWorkordeData) && selWorkordeData.isEmpty()){
				map.put("msg", "您的订单不存在");
				return map;
			}
			
			String totalMoney = selWorkordeData.get("totalMoney").toString();
			//根据userid 查询账户表 返回'accountId,cash,kaiyuan' 字段
			Account selUserAccount = iAccountService.selectAccountByuserId(userId);
			if(ToolUtil.isEmpty(selUserAccount)){
				map.put("msg", "账户表不存在");
				return map;
			}
			
			//判断前台传入的  paytype 是什么类型（账户现金。账户华宝。华宝营业额）再根据不同类型存入日志表
			//支付方式 2 现金账户支付 3开元宝支付 6开元宝营业额
			BigDecimal totalMonerRet = new BigDecimal(0);// 现金
			BigDecimal kaiyuanRet = new BigDecimal(0);// 华宝
			BigDecimal kaiyuanTurnRet = new BigDecimal(0);// 华宝货款
			if(payType == 2){
				//判断现金是否可以支付
				BigDecimal totalMoner = new BigDecimal(selWorkordeData.get("totalMoney").toString());
				totalMonerRet = totalMoner;
				if(selUserAccount.getCash().compareTo(totalMoner)==-1){
					map.put("msg", "用户现金余额不足");
					return map;
				}
				//新增现金流水表
				boolean insertLogCash = iAccountService.insertLogCash(-1,0,userId,orderNo,selUserAccount.getCash(),"支付工单服务费",12,totalMoner);
				
				//修改用户账户表
				BigDecimal surplusCash = new BigDecimal(0);
				surplusCash = selUserAccount.getCash().subtract(totalMoner);//剩余
				selUserAccount.setCash(surplusCash);
				iAccountService.updateById(selUserAccount);
				
				//修改工单表 orderid,status,paytype,cash
				SktWorkorder sw = new SktWorkorder();
				sw = sktWorkorderMapper.selectById(Integer.parseInt(selWorkordeData.get("orderId").toString()));
				sw.setStatus(1);
				sw.setPayType(payType);
				sw.setCash(totalMoner);
				sktWorkorderMapper.updateById(sw);

			}else if(payType == 3){
				SktSysConfigs taxRatio = sktSysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");//综合服务费%
				String  taxRatios=taxRatio.getFieldValue();//综合服务费用
				BigDecimal ratio=new BigDecimal(taxRatios);
				SktSysConfigs kaiyuanFee = sktSysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");//华宝支付手续费%
				String  huabaoFee=kaiyuanFee.getFieldValue();//华宝支付费用
				BigDecimal hb=new BigDecimal(huabaoFee);
				BigDecimal hbFee=hb.add(ratio);
				//转换华宝
				BigDecimal totalKaiyuan=new BigDecimal(totalMoney).multiply(new BigDecimal(100));
				//手续费
				BigDecimal kaiyuanFe=totalKaiyuan.multiply(hbFee.divide(new BigDecimal(100))).setScale(3, BigDecimal.ROUND_DOWN);
				//综合费
				BigDecimal kaiyuanZhFe = totalKaiyuan.multiply(ratio.divide(new BigDecimal(100))).setScale(3, BigDecimal.ROUND_DOWN);
				//开元费
				BigDecimal kaiyuanfei = kaiyuanFe.add(kaiyuanZhFe);
				//总开元宝
				BigDecimal zongKaiyuan = totalKaiyuan.add(kaiyuanfei);
				
				kaiyuanRet = zongKaiyuan;//华宝金额
				if(selUserAccount.getKaiyuan().compareTo(totalKaiyuan) == -1){
					map.put("msg", "华宝余额不足");
					return map;
				}
				//华宝流水服务费
				boolean insertLogKaiyuan = iAccountService.insertLogKaiyuan(0,totalKaiyuan,-1,orderNo,selUserAccount.getKaiyuan(),"支付工单服务费",6,userId);
				//华宝流水手续费
				boolean insertLogKaiyuanSX = iAccountService.insertLogKaiyuan(0,kaiyuanfei,-1,orderNo,selUserAccount.getKaiyuan(),"支付工单手续费",8,userId);
				
				//修改用户账户表
				BigDecimal surplusCash = new BigDecimal(0);
				surplusCash = selUserAccount.getKaiyuan().subtract(zongKaiyuan);
				selUserAccount.setKaiyuan(surplusCash);
				iAccountService.updateById(selUserAccount);
				//修改工单表 orderid,status,paytype,Kaiyuan
				SktWorkorder sw = new SktWorkorder();
				sw = sktWorkorderMapper.selectById(Integer.parseInt(selWorkordeData.get("orderId").toString()));
				sw.setStatus(1);
				sw.setPayType(payType);
				sw.setKaiyuan(zongKaiyuan);
				sktWorkorderMapper.updateById(sw);
				
			}else if(payType == 6){
				SktSysConfigs kaiyuanturnFee = sktSysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");//华宝货款支付手续费%
				String  huabaoturnFee=kaiyuanturnFee.getFieldValue();//华宝货款支付费用
				BigDecimal huabaoturnFeeRatio=new BigDecimal(huabaoturnFee);
				BigDecimal totalMoneyBigDec = new BigDecimal(totalMoney);
				
				//要支付的华宝货款
				BigDecimal zfKaiYuanTurn = totalMoneyBigDec.multiply(new BigDecimal(100)).setScale(3, BigDecimal.ROUND_CEILING);
				//手续费=（要支付的华宝货款*（华宝货款手续费比例除100）留小数点后三位）
				BigDecimal shouKaiYuanFee = zfKaiYuanTurn.multiply(huabaoturnFeeRatio.divide(new BigDecimal(100))).setScale(3, BigDecimal.ROUND_CEILING);
				//总华宝货款=要支付的华宝货款+手续费
				BigDecimal zongKaiYuanTurn = zfKaiYuanTurn.add(shouKaiYuanFee);
				
				kaiyuanTurnRet = zongKaiYuanTurn;
				//根据userID 查询店铺商户表 下的'accountId,kaiyuanTurnover' 字段 
				AccountShop accountShop = iAccountShopService.selectByUserId(userId);
				// 判断华宝货款余额是否充足
				if(accountShop.getKaiyuanTurnover().compareTo(zongKaiYuanTurn)==-1){
					map.put("msg", "您的华宝货款余额不足！");
					return map;
				}
				
				//华宝货款流水
				//Integer type,Integer fromId,Integer userId,String orderNo,BigDecimal preKaiyuan,Integer kaiyuanType,BigDecimal kaiyuan,String remark
				iAccountService.insertLogKaiYuanTurnover(7,0,userId,orderNo,accountShop.getKaiyuanTurnover(),-1,zfKaiYuanTurn,"支付工单服务费");
				//华宝货款费用流水
				iAccountService.insertLogKaiYuanTurnover(9,0,userId,orderNo,accountShop.getKaiyuanTurnover(),-1,shouKaiYuanFee,"支付工单服务费");
				//店铺账户表修改（"accountId" => 店铺账户表下的['accountId']）
				BigDecimal surpluskaiyuanTurnover = accountShop.getKaiyuanTurnover().subtract(zongKaiYuanTurn);
				accountShop.setKaiyuanTurnover(surpluskaiyuanTurnover);
				iAccountShopService.updateById(accountShop);
				
				//工单表
				SktWorkorder sw = new SktWorkorder();
				sw = sktWorkorderMapper.selectById(Integer.parseInt(selWorkordeData.get("orderId").toString()));
				sw.setStatus(1);
				sw.setPayType(payType);
				sw.setKaiyuan(zongKaiYuanTurn);
				sktWorkorderMapper.updateById(sw);
				
			}
			
			map.put("orderNo", orderNo);
			map.put("totalMoney", totalMonerRet);
			map.put("kaiyuan", kaiyuanRet);
			map.put("kaiyuanTurn", kaiyuanTurnRet);
			map.put("createTime", new Date());
			return map;
		}catch(Exception e){
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			Map<String,Object> map = new HashMap<>();
			map.put("orderNo", orderNo);
			map.put("totalMoney", "");
			map.put("kaiyuan", "");
			map.put("kaiyuanTurn", "");
			map.put("createTime", new Date());
			return map;
		}
	}
	@Override
	public Map<String, Object> getWorkorder(Users user) {
		Map<String,Object> map = new HashMap<>();//传值
		Map<String,Object> mapRet = new HashMap<>();//返回值
		map.put("userId", user.getUserId());
		
		//查询分享人状态
		map.put("type", 1);
		String shareStatus = sktWorkorderMapper.getWorkorder(map);
		
		//查询电话状态 
		map.put("type", 2);
		String phoneStatus = sktWorkorderMapper.getWorkorder(map);
		if(MSGUtil.isBlank(shareStatus)){
			mapRet.put("shareStatus", 10);//0：未支付；1：已付款；10：暂无工单数据；
		}else{
			mapRet.put("shareStatus", shareStatus);
		}
		
		if(MSGUtil.isBlank(phoneStatus)){
			mapRet.put("phoneStatus", 10);//0：未支付；1：已付款；10：暂无工单数据；
		}else{
			mapRet.put("phoneStatus", phoneStatus);
		}
		Users selectById = iUsersService.selectById(user.getUserId());
		mapRet.put("inviteId", selectById.getInviteId());
		
		return mapRet;
	}
	@Override
	public Map<String, Object> getShare(Users user) {
		Map<String,Object> mapRet = new HashMap<>();
		//查询工单状态status
		Map<String,Object> map = new HashMap<>();
		map.put("userId", user.getUserId());
		map.put("type", 1);
		String sStauts = sktWorkorderMapper.getShare(map);
		Integer iStauts = 0;
		if(MSGUtil.isBlank(sStauts)){
			iStauts = 10;
		}else{
			iStauts = Integer.parseInt(sStauts);
		}
		
		switch (iStauts) {
			case 0:
				mapRet.put("msg", "您还有未支付的工单");
				return mapRet;
			case 1:
				mapRet.put("msg", "您还有未处理的工单");
				return mapRet;
			case 3:
				mapRet.put("msg", "您不能使用此功能");
				return mapRet;
		}
		//查询users表 返回用户的推荐人ID， 推荐人登录名 ，推荐人电话
		Map<String,Object> tuiJianInfo = sktWorkorderMapper.selectTuiJianInfo(map);
		if(!MSGUtil.isBlank(tuiJianInfo)){
			mapRet.put("msg", "您不能使用此功能");
			return mapRet;
		}
		//查询工单费
		String findFieldValue = sktSysConfigsMapper.findFieldValue("workOrderFee");
		mapRet.put("inviteId", 0);
		mapRet.put("loginName", "平台");
		mapRet.put("userPhone", "平台");
		mapRet.put("modifyMes", "分享人信息");
		mapRet.put("workOrderFee", findFieldValue);
		return mapRet;
	}
	@Override
	public Map<String, Object> modifyShare(String preValue, String afterValue, String orderRemarks, String imgs,
			Integer money,Users user) {
		Map<String,Object> mapRet = new HashMap<>();
		//查询afterValue  （现分享人用户名或手机号） 
		//返回userID loginname as shareinfo
		Map<String,Object> map = iUsersService.selectIdLoginNameShareInfo(afterValue);
		if(map==null||map.isEmpty()|| MSGUtil.isBlank(map)){
			mapRet.put("msg", "新分享用户不存在");
			return mapRet;
		}
		//判断用户是不是本人
		if(Integer.parseInt(map.get("userId").toString())==user.getUserId()){
			mapRet.put("msg", "新分享用户不能是本人");
		}
		//查询工单费
		String findFieldValue = sktSysConfigsMapper.findFieldValue("workOrderFee");
		//判断工单是不是相同
		Integer ifindfiedValue = Integer.parseInt(findFieldValue);
		if(money.intValue() != ifindfiedValue.intValue()){
			mapRet.put("msg", "工单费用不符合要求");
			return mapRet;
		}
		
		//新增工单表
		String orderNo = StringUtils.getOrderIdByTime("2");//生成订单号
		SktWorkorder sktWorkorder = new SktWorkorder();
		sktWorkorder.setOrderNo(orderNo);
		sktWorkorder.setUserId(user.getUserId());
		sktWorkorder.setType(1);
		sktWorkorder.setPreValue(preValue);
		sktWorkorder.setAfterValue(afterValue);
		sktWorkorder.setOrderRemarks(orderRemarks);
		sktWorkorder.setImgs(imgs);
		sktWorkorder.setPayType(0);
		sktWorkorder.setTotalMoney(new BigDecimal(money));
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化日期
		String dateString = formatter.format(currentTime);
		sktWorkorder.setCreateTime(dateString);
		sktWorkorder.setStatus(0);
		sktWorkorder.setDataFlag(1);
		
		Integer insert = sktWorkorderMapper.insert(sktWorkorder);
		
		if(insert.intValue() == 0){
			mapRet.put("msg", "新增工单失败");
			return mapRet;
		}
		mapRet.put("orderNo", orderNo);
		mapRet.put("sceneCode", "WORK_ORDER");
		mapRet.put("payMoney", money);
		return mapRet;
	}
	@Override
	public Map<String, Object> getPhone(Users user) {
		Map<String,Object> mapRet = new HashMap<>();
		//查询工单状态status
		Map<String,Object> map = new HashMap<>();
		map.put("userId", user.getUserId());
		map.put("type", 2);
		SktWorkorder sktWorkorder = sktWorkorderMapper.getPhone(map);
		if(!MSGUtil.isBlank(sktWorkorder)){//如果不为空 
			mapRet.put("msg", "您还有未处理的工单");
		}
		//如果为空 查询用户手机号
		Users uer = iUsersService.selectById(user.getUserId());
		if(MSGUtil.isBlank(uer)){
			mapRet.put("msg", "用户手机号不存在");
			return mapRet;
		}
		//查询工单费
		String findFieldValue = sktSysConfigsMapper.findFieldValue("workOrderFee");
		//返回值
		mapRet.put("userPhone", uer.getUserPhone());
		mapRet.put("modifyMes", "手机号");
		mapRet.put("workOrderFee", findFieldValue);
		return mapRet;
	}
	@Override
	public Map<String, Object> modifyPhone(String preValue, String afterValue, String code, String function,
			String orderRemarks, String imgs, Integer money, Users user) {
		Map<String,Object> mapRet = new HashMap<>();
		//根据前台传过来的新手机号 查询users表  判断新手机号有没有被注册
		Users users = new Users();
		users.setUserPhone(afterValue);
		EntityWrapper<Users> ew = new EntityWrapper<>(users);
//		ew.where("userPhone", afterValue);
		List<Users> selectList = iUsersService.selectList(ew);
		if(MSGUtil.isBlank(selectList) && selectList.size()>0){
			mapRet.put("msg", "新手机号已经被注册");
			return mapRet;
		}
		//给新手机号发送短信验证码
		Object code1 = cacheUtil.get(afterValue);
		if(code1 == null || !code1.toString().equals(code)){
			mapRet.put("msg", "短信校验失败");
            return mapRet;
		}
		//判断工单服务费是否有误
		//查询工单费
		String findFieldValue = sktSysConfigsMapper.findFieldValue("workOrderFee");
		//判断工单是不是相同
		Integer ifindfiedValue = Integer.parseInt(findFieldValue);
		if(money.intValue() != ifindfiedValue.intValue()){
			mapRet.put("msg", "工单费用不符合要求");
			return mapRet;
		}
		//插入工单表
		String orderNo = StringUtils.getOrderIdByTime("3");//生成订单号
		SktWorkorder sktWorkorder = new SktWorkorder();
		sktWorkorder.setOrderNo(orderNo);
		sktWorkorder.setUserId(user.getUserId());
		sktWorkorder.setType(1);
		sktWorkorder.setPreValue(preValue);
		sktWorkorder.setAfterValue(afterValue);
		sktWorkorder.setOrderRemarks(orderRemarks);
		sktWorkorder.setImgs(imgs);
		sktWorkorder.setPayType(0);
		sktWorkorder.setTotalMoney(new BigDecimal(money));
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化日期
		String dateString = formatter.format(currentTime);
		sktWorkorder.setCreateTime(dateString);
		sktWorkorder.setStatus(0);
		sktWorkorder.setDataFlag(1);
		
		Integer insert = sktWorkorderMapper.insert(sktWorkorder);
		
		if(insert.intValue() == 0){
			mapRet.put("msg", "新增工单失败");
			return mapRet;
		}
		mapRet.put("orderNo", orderNo);
		mapRet.put("sceneCode", "WORK_ORDER");
		mapRet.put("payMoney", money);
		return mapRet;
	}
	
	
}
